package com.dragon.www.haier.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;

/**
 * Created by Administrator on 2015/10/29 09:53.
 * Author: songxy
 * Email: thinkdata@163.com
 */
public class AppSocket {

	private final DatagramSocket socket;
	/**
	 * 包大小
	 */
	private static final int PACKET_BUFFER_SIZE = 524288;
	/**
	 * 连接状态
	 */
	protected boolean isUdpConnected = false;

	public AppSocket(DatagramSocket socket) {
		this.socket = socket;
	}

	public boolean isBound() {
		return this.socket != null && this.socket.isBound() ? true : false;
	}

	public void sendMsgToNetwork(AUDPPacket packet, boolean isNew) throws IOException {
		DatagramPacket outPacket;
		if (isNew) {
			outPacket = packet.newPacket(PACKET_BUFFER_SIZE);
		}else {
			outPacket = packet.newPacket();
		}

		packet.writePacketObject(outPacket);
		this.socket.send(outPacket);
	}

	public void sendMsgToNetwork(AUDPPacket packet) throws IOException {
		DatagramPacket outPacket = packet.newPacket(PACKET_BUFFER_SIZE);
		packet.writePacketObject(outPacket);
		this.socket.send(outPacket);
	}

	public AUDPPacket receiveMsgFromNetwork(AUDPPacket packet) throws IOException {
		try {
			DatagramPacket inPacket = packet.newPacket();
			this.socket.receive(inPacket);
			ByteBuffer bb = packet.readPacketHeader(inPacket);
			if (bb != null) {
				packet.readPacketObject(bb);
				packet.readPacketTail(bb);
			}
		}catch (IOException e) {
			if (e instanceof SocketTimeoutException) {
				throw e;
			}else {
				throw new IOException("Receive Msg From Remote Error "+e.getMessage());
			}
		}catch (ClassNotFoundException e) {
			throw new IOException("Receive Msg External Class Not Found "+e.getMessage());
		}catch (NullPointerException e) {
			throw new IOException("this.socket is null "+e.getMessage());
		}
		return packet;
	}

	public DatagramPacket receiveRawMsgFromNetwork(AUDPPacket packet) throws IOException {
		try {
			DatagramPacket inPacket = packet.newPacket();
			this.socket.receive(inPacket);
			return inPacket;
		}catch (IOException e) {
			if (e instanceof SocketTimeoutException) {
				throw e;
			}else {
				throw new IOException("Receive Msg From Remote Error "+e.getMessage());
			}
		}catch (NullPointerException e) {
			throw new IOException("this.socket is null "+e.getMessage());
		}
	}


	public SocketAddress getSocketInetAddress() {
		return this.socket.getRemoteSocketAddress();
	}

	public boolean isClosed() {
		return (this.socket != null && this.socket.isClosed()) ? true : false;
	}


	public void close() {
		this.socket.close();
	}
}
